package com.tarena.lbs.coupon.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.activity.api.ActivityApi;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.coupon.api.pojo.param.UserCouponsParam;
import com.tarena.lbs.coupon.dao.mapper.CouponMapper;
import com.tarena.lbs.coupon.dao.mapper.StockMapper;
import com.tarena.lbs.coupon.dao.repository.CouponCodeRepository;
import com.tarena.lbs.coupon.dao.repository.CouponRepository;
import com.tarena.lbs.coupon.dao.repository.UserCouponsRepository;
import com.tarena.lbs.coupon.pojo.param.CouponParam;
import com.tarena.lbs.coupon.pojo.po.CouponPO;
import com.tarena.lbs.coupon.pojo.po.CouponStockPO;
import com.tarena.lbs.coupon.pojo.po.UserCouponsPO;
import com.tarena.lbs.coupon.pojo.query.UserCouponCodeQuery;
import com.tarena.lbs.coupon.pojo.vo.CouponVO;
import com.tarena.lbs.coupon.pojo.vo.UserCouponsVO;
import com.tarena.lbs.coupon.service.CouponService;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
@Transactional
@Service
@Slf4j
public class CouponServiceImpl implements CouponService {


    @Autowired
    private CouponRepository couponRepository;

    @Autowired
    private UserCouponsRepository userCouponsRepository;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private CouponMapper couponMapper;

    @DubboReference
    private ActivityApi activityApi;

    @DubboReference
    private UserApi userApi;

    /**
     * 新增优惠券
     * @param couponParam
     * @throws BusinessException
     */
    @Override
    public void save(CouponParam couponParam) throws BusinessException {
        CouponPO poParam = assembleCouponPO(couponParam);
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
//        if(null!=userPrinciple){
//            Integer id = userPrinciple.getId();
//            AdminDto adminDto=userApi.getAdminById(id);
//            poParam.setBusinessId(adminDto.getBusinessId());
//        }

        poParam.setBusinessId(22);
        poParam.setEnableStatus(1);
        int couponId=couponRepository.save(poParam);
        CouponStockPO couponStockPO=new CouponStockPO();
        couponStockPO.setBusinessId(couponParam.getBusinessId());
        couponStockPO.setNum(couponParam.getMaxUsageLimit());
        couponStockPO.setCreateAt(new Date());
        couponStockPO.setCouponId(couponId);
        couponStockPO.setBusinessId(22);
        stockMapper.insert(couponStockPO);
    }


    @Override
    public PageResult<CouponVO> pageList(CouponParam couponParam) {
        // 创建一个新的分页结果对象，用于存储最终的分页查询结果
        PageResult<CouponVO> voPage = new PageResult<>();
        //total objects pageNo pageSize totalPage
        // 调用 adminRepository 的 gePages 方法进行分页查询，获取包含管理员持久化对象的分页信息
        PageInfo<CouponPO> pageInfo = couponRepository.pagesList(couponParam);
        //pageNo pageSize total
        // 将分页信息中的页码设置到分页结果对象中
        voPage.setPageNo(pageInfo.getPageNum());
        // 将分页信息中的每页数量设置到分页结果对象中
        voPage.setPageSize(pageInfo.getPageSize());
        // 将分页信息中的总记录数设置到分页结果对象中
        voPage.setTotal(pageInfo.getTotal());
        // 声明一个存储管理员视图对象的列表
        List<CouponVO> vos = null;
        // 从分页信息中获取管理员持久化对象列表
        List<CouponPO> pos = pageInfo.getList();
        // 判断持久化对象列表是否不为空
        if (CollectionUtils.isNotEmpty(pos)){
            vos=pos.stream().map(po->{
                CouponVO vo = new CouponVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        voPage.setObjects(vos);
        return voPage;
    }


    /**
     * 用户领取优惠券
     * @param userCouponsParam
     * @throws BusinessException
     */
    @Override
    public void UserCouponsSave(UserCouponsParam userCouponsParam) throws BusinessException {
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
//        Integer id = userPrinciple.getId();
        UserCouponsPO userCouponsPO=assembleUserCouponsPO(userCouponsParam);
        Boolean b=activityApi.activityVisible(userCouponsParam.getActivityId(),1);
        couponRepository.UserCouponsSave(userCouponsPO);



    }


    @Override
    public PageResult<UserCouponsVO> pageUserCouponsList() {
        // 创建一个新的分页结果对象，用于存储最终的分页查询结果
        PageResult<UserCouponsVO> voPage = new PageResult<>();
        PageInfo<UserCouponsVO> pageInfo = couponRepository.pageUserCouponsList();
        // 将分页信息中的页码设置到分页结果对象中
        voPage.setPageNo(pageInfo.getPageNum());
        // 将分页信息中的每页数量设置到分页结果对象中
        voPage.setPageSize(pageInfo.getPageSize());
        // 将分页信息中的总记录数设置到分页结果对象中
        voPage.setTotal(pageInfo.getTotal());
        voPage.setObjects(pageInfo.getList());
        return voPage;
    }


    /**
     *查询某优惠券二维码
     * @param param
     * @return
     * @throws BusinessException
     */
    @Override
    public UserCouponsVO receiveDetail(UserCouponCodeQuery param) throws BusinessException {
        return userCouponsRepository.receiveDetail(param);

    }

    @Override
    public void updateCouponStatus(CouponParam couponParam) throws BusinessException {

        couponRepository.updateCouponStatus(couponParam);
    }


    /**
     * 编辑优惠券
     * @param couponParam
     * @throws BusinessException
     */
    @Override
    public void updateCoupon(CouponParam couponParam) throws BusinessException {
        couponRepository.updateCoupon(couponParam);

    }

    /**
     * 删除优惠券
     * @param couponParam
     * @throws BusinessException
     */
    @Override
    public void deleteCoupon(CouponParam couponParam) throws BusinessException {
        couponRepository.deleteCoupon(couponParam);

    }

    @Override
    public CouponVO detail(int CouponParam) {
        return couponRepository.detail(CouponParam);
    }


    @Override
    public List<Map<String, Object>> selectAllCoupons() {
        return couponMapper.selectAllCoupons();
    }

    private UserCouponsPO assembleUserCouponsPO(UserCouponsParam param) throws BusinessException {


        String uuid = UUID.randomUUID().toString();
        UserCouponsPO po=new UserCouponsPO();
        po.setCouponValue(new BigDecimal(5));
        po.setCouponType(1);
        po.setStatus(0);
        po.setCreateAt(new Date());
        po.setUpdateAt(new Date());
        BeanUtils.copyProperties(param,po);
        po.setCouponId(param.getCouponId());
        po.setUserId(1);
        po.setActivityId(param.getActivityId());
        po.setShopId(param.getShopId());
        po.setCouponUrl("https://images-p.codeboy.com/lbs_attach/0126ae68bdd7420ba17c1a0f84fba563.png");
        po.setCouponCode(uuid);
        return po;
    }

    private CouponPO assembleCouponPO(CouponParam param) {
        CouponPO po=new CouponPO();
        po.setStartDate(new Date());
        po.setEndDate(new Date());
        po.setStatus(1);
        po.setCreateAt(new Date());
        po.setEndDate(new Date());
        po.setEnableStatus(3);
        BeanUtils.copyProperties(param,po);
        return po;
    }
}
